#define _CRT_SECURE_NO_WARNINGS 1

//
#include <vector>
#include <stack>
using namespace std;
  struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode() : val(0), left(nullptr), right(nullptr) {}
      TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
      TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  };
 
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        TreeNode* pcur = root;
        stack<TreeNode*> st;
        vector<int> v;
        TreeNode* prev = nullptr;
        while (pcur || !st.empty())
        {
            while (pcur)
            {
                st.push(pcur);
                pcur = pcur->left;
            }
            pcur = st.top()->right;
            if (!pcur)
            {
                prev = st.top();
                v.push_back(prev->val);
                st.pop();
            }
            else
            {
                if (pcur == prev)
                {
                    prev = st.top();
                    v.push_back(prev->val);
                    st.pop();
                    pcur = nullptr;
                }
            }
        }
        return v;
    }
};